package org.cosmact.designer.xml.utils;

import java.io.InputStream;
import java.io.StringReader;
import java.util.List;

import org.cosmact.common.utils.Utilities;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
 * Util to parse xml.
 * 
 *@author hsieh 234aini@gmail.com
 * 
 */
public class XmlUtil {

	public static Document parse(String content) throws DocumentException {
		if (Utilities.isNullOrEmpty(content)) {
			throw new IllegalArgumentException();
		}
		SAXReader reader = new SAXReader();
		return reader.read(new StringReader(content));
	}

	public static Document parse(InputStream content) throws DocumentException {
		if (content == null) {
			throw new IllegalArgumentException();
		}
		SAXReader reader = new SAXReader();
		Document read = reader.read(content);
		return read;
	}

	/**
	 * <strong style="color:red">This operation is not support xml element with
	 * namespaces.</strong>
	 * 
	 * @param document
	 * @param path
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List selectedNodes(Document document, final String path) {
		if (document == null) {
			throw new IllegalArgumentException("document");
		}

		if (Utilities.isNullOrEmpty(path)) {
			throw new IllegalArgumentException("xpath");
		}

		return document.selectNodes(path);
	}
}
